<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="机构名称" prop="mechanismName">
        <el-input
          v-model="queryParams.mechanismName"
          placeholder="请输入机构名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="银行账号" prop="bankAccount">
        <el-input
          v-model="queryParams.bankAccount"
          placeholder="请输入银行账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="开户行" prop="bankName">
        <el-input
          v-model="queryParams.bankName"
          placeholder="请输入开户行"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="联系人" prop="contactsName">
        <el-input
          v-model="queryParams.contactsName"
          placeholder="请输入联系人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="contactsPhone">
        <el-input
          v-model="queryParams.contactsPhone"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="申请认证时间" prop="applyTime">
        <el-date-picker clearable
          v-model="queryParams.applyTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择申请认证时间">
        </el-date-picker>
      </el-form-item> -->
      <!-- <el-form-item label="认证通过时间" prop="applyDoneTime">
        <el-date-picker clearable
          v-model="queryParams.applyDoneTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择认证通过时间">
        </el-date-picker>
      </el-form-item> -->
      <!-- <el-form-item label="父级机构ID" prop="parentId">
        <el-input
          v-model="queryParams.parentId"
          placeholder="请输入父级机构ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="${comment}" prop="qrCode">
        <el-input
          v-model="queryParams.qrCode"
          placeholder="请输入${comment}"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['customer:mechanism:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['customer:mechanism:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['customer:mechanism:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['customer:mechanism:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-if="refreshTable" v-loading="loading" :data="mechanismList"  row-key="mechanismId"
      :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="${comment}" align="center" prop="mechanismId" /> -->
      <el-table-column label="机构名称" align="center" prop="mechanismName" width="100"/>
      <el-table-column label="银行账号" align="center" prop="bankAccount" width="100"/>
      <el-table-column label="开户行" align="center" prop="bankName" />
      <el-table-column label="营业执照副本图片" align="center" prop="businessLicense" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.businessLicense" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <!-- <el-table-column label="机构审核状态" align="center" prop="examineStatus" /> -->
      <el-table-column label="联系人" align="center" prop="contactsName" />
      <el-table-column label="联系方式" align="center" prop="contactsPhone" width="110"/>
      <el-table-column label="申请认证时间" align="center" prop="applyTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="认证通过时间" align="center" prop="applyDoneTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applyDoneTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="父级机构ID" align="center" prop="parentId" /> -->
      <el-table-column label="二维码" align="center" prop="qrCode" >
        <template slot-scope="scope">
          <image-preview :src="scope.row.qrCode" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="分享链接" align="center" width="200">
        <template slot-scope="scope" >
          <el-button
            size="medium"
            height="200"
            @click="handleCopy(scope.row)">
            <div class="share">{{scope.row.shareUrl}}</div>
          </el-button>
        </template>
       </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['customer:mechanism:edit']"
          >修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)"
            v-hasPermi="['customer:mechanism:add']">新增</el-button>
            <el-button size="mini" type="text"  @click="handleQrcode(scope.row)"
            >生成二维码</el-button>
          <el-button
          v-if="scope.row.parentId != 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['customer:mechanism:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改机构信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级机构名称" prop="parentId">
              <treeselect v-model="form.parentId" :options="categoryOptions" :normalizer="normalizer"
                placeholder="选择上级机构" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="机构名称" prop="mechanismName">
          <el-input v-model="form.mechanismName" placeholder="请输入机构名称" />
        </el-form-item>
        <el-form-item label="银行账号" prop="bankAccount">
          <el-input v-model="form.bankAccount" placeholder="请输入银行账号" />
        </el-form-item>
        <el-form-item label="开户行" prop="bankName">
          <el-input v-model="form.bankName" placeholder="请输入开户行" />
        </el-form-item>
        <el-form-item label="营业执照副本图片" prop="businessLicense">
          <ImageUpload @success="handleImg"
              :limit="1"
              :value="form.businessLicense"/>
        </el-form-item>
        <el-form-item label="联系人" prop="contactsName">
          <el-input v-model="form.contactsName" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系方式" prop="contactsPhone">
          <el-input v-model="form.contactsPhone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="申请认证时间" prop="applyTime">
          <el-date-picker clearable
            v-model="form.applyTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择申请认证时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="认证通过时间" prop="applyDoneTime">
          <el-date-picker clearable
            v-model="form.applyDoneTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择认证通过时间">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="父级机构ID" prop="parentId">
          <el-input v-model="form.parentId" placeholder="请输入父级机构ID" />
        </el-form-item> -->
        <!-- <el-form-item label="二维码" prop="qrCode">
          <el-input v-model="form.qrCode" placeholder="请输入${comment}" />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMechanism, getMechanism, delMechanism, addMechanism, updateMechanism,generateCode,getMechanismTree } from "@/api/customer/mechanism";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "Mechanism",
  components: { Treeselect },
  data() {
    return {
      copyData:null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 机构信息表格数据
      mechanismList: [],
      categoryOptions: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      Erqrcode:'',
      imgUrl: process.env.VUE_APP_BASE_API,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        mechanismName: null,
        bankAccount: null,
        bankName: null,
        businessLicense: null,
        examineStatus: null,
        contactsName: null,
        contactsPhone: null,
        applyTime: null,
        applyDoneTime: null,
        parentId: null,
        qrCode: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      // 表单校验
      rules: {
        // parentId: [
        //   { required: true, message: "上级机构名称不能为空", trigger: "blur" }
        // ],
        mechanismName: [
          { required: true, message: "机构名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    
    
  },
  methods: {
    /** 查询机构信息列表 */
    getList() {
      this.loading = true;
      listMechanism(this.queryParams).then(response => {
        console.log('response',response);
        this.mechanismList = response.rows;
        // this.mechanismList = this.handleTree(response.rows, "mechanismId");
        console.log('this.mechanismList',this.mechanismList);
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        mechanismId: null,
        mechanismName: null,
        bankAccount: null,
        bankName: null,
        businessLicense: null,
        examineStatus: null,
        contactsName: null,
        contactsPhone: null,
        applyTime: null,
        applyDoneTime: null,
        parentId: null,
        qrCode: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.label,
        children: node.children
      };
    },
     /** 展开/折叠操作 */
     toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    // handleSelectionChange(selection) {
    //   this.ids = selection.map(item => item.mechanismId)
    //   this.single = selection.length!==1
    //   this.multiple = !selection.length
    // },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      console.log('row',row);
      if (row != undefined) {
        this.form.parentId = row.mechanismId;
        console.log('row',this.form.parentId);
      }
      this.open = true;
      this.title = "添加机构信息";

      getMechanismTree().then(response => {
        console.log('response2',response);
        this.categoryOptions = response.data;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      if (row.mechanismId == row.parentId) {
        this.$modal.msgError("不能选择自己作为父节点");
        return;
      }
      getMechanismTree().then(response => {
        console.log('response2',response);
        this.categoryOptions = response.data;
      });
      const mechanismId = row.mechanismId || this.ids
      getMechanism(mechanismId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改机构信息";
      });
    },
    /** 生成二维码 */
    handleQrcode(row){
      console.log(row);
      var requestObj = {};
      requestObj.mechanismId = row.mechanismId;
      generateCode(requestObj).then((res)=>{
        console.log('res',res);
        this.getList();
      })
    },
    // 复制链接
    handleCopy(row){
      this.copyData = row.shareUrl
      this.copy(this.copyData)
    },
    // 处理图片上传
    handleImg(file) {
      console.log('tutuuu',file);
      this.form.businessLicense = file;
      // this.getList();
    },
    copy(data){
        let url = data;
        let oInput = document.createElement('input');
        oInput.value = url;
        document.body.appendChild(oInput);
        oInput.select(); // 选择对象;
        console.log(oInput.value)
        document.execCommand("Copy"); // 执行浏览器复制命令
        this.$message({
          message: '复制成功',
          type: 'success'
        });
        oInput.remove()
      },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.mechanismId != null) {
            updateMechanism(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if(this.form.parentId == undefined){
              this.form.parentId = 0
            }
            console.log('this.form',this.form);
            addMechanism(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const mechanismIds = row.mechanismId || this.ids;
      this.$modal.confirm('是否确认删除机构信息编号为"' + mechanismIds + '"的数据项？').then(function() {
        return delMechanism(mechanismIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('customer/mechanism/export', {
        ...this.queryParams
      }, `mechanism_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.el-table{
  font-size: 11px;
}
.share{
  width: 100px;
  white-space:normal; word-break:break-all;
}
.el-button--medium{
  border: none;
}
</style>